<template>
  <div :class="['mix-content', { 'unfold': !isUnfold }]">
    <i v-if="isUnfold" class="wk wk-close" @click="close"/>
    <div v-if="isUnfold" class="mix-content-select">
      <el-select v-if="showContacts" v-model="selectContactsId" clearable placeholder="选择联系人">
        <el-option v-for="item in contacts" :key="item.contactsId" :label="item.name" :value="item.contactsId"/>
      </el-select>
      <el-select v-model="followType" clearable placeholder="选择跟进方式">
        <el-option v-for="item in followTypes" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>
      <el-date-picker ref="refNextTime" v-model="nextTime" :editable="false" type="datetime" @focus="focusStart"
                      placeholder="选择下次联系时间"
                      value-format="YYYY-MM-DD HH:mm:ss"/>
      <!--常用语-->
      <CommonWords @select="commonWordsSelect"/>
    </div>
    <div :class="['i-cont', { 'unfold': !isUnfold }]">
      <i v-if="!isUnfold" class="wk wk-write"/>
      <el-input ref="textarea" input-style="{border: none;}"
                v-model="content"
                :autosize="autosize"
                :maxlength="800"
                type="textarea"
                clearable
                resize="none"
                placeholder="请输入内容"
                @focus="inputFocus"/>
    </div>
    <AddImageList v-if="imgFiles.length > 0 && isUnfold" :data="imgFiles"
                    @delete="deleteImage"
                    @delete-all="deleteAllFile(2)"
                    @upload="uploadFile"/>
    <AddFileList v-if="files.length > 0 && isUnfold" :data="files"
                   @delete="deleteFile"
                   @delete-all="deleteAllFile(1)"/>
    <AddRelateList v-if="business.length > 0 && isUnfold" :data="business"
                     type="business"
                     @delete="deleteRelate"/>

    <div v-if="isUnfold" class="bar-cont">
      <el-button link class="handle-button" @click="barClick('img')">
        <el-icon><Picture /></el-icon>图片
      </el-button>
      <el-button link class="handle-button" @click="barClick('file')">
        <el-icon><Files /></el-icon>附件
      </el-button>
      <CrmRelative v-if="showBusiness" v-model:visible="showBusinessPopover"
                    :radio="false"
                    :action="businessAction"
                    :selected-data="{ 'business': business }"
                    crm-type="business"
                    @close="showBusinessPopover=false"
                    @changeCheckout="checkRelativeInfos"/>
      <el-button link class="handle-button" style="margin-left: 10px;" @click="barClick('business')">
        <el-icon><Link /></el-icon>关联商机
      </el-button>
      <el-button v-debounce="sendClick" type="primary" class="send-btn">发布</el-button>
    </div>

    <!-- 附件 -->
    <input ref="fileInput" accept="*.*"
           type="file" class="file-input" multiple @change="uploadFile">
    <input ref="imgInput" accept="image/*"
           type="file" class="file-input" multiple @change="uploadFile">
  </div>
</template>

<script setup>

import CrmRelative from '/src/components/CreateCom/CrmRelative.vue'
import {ref, getCurrentInstance, nextTick, watch, computed} from "vue"
import {crmFileDeleteAPI, crmFileRemoveByBatchIdAPI} from '@/api/common.js'

import AddImageList from '/src/szcomponent/QuickAdd/AddImageList'
import AddFileList from '/src/szcomponent/QuickAdd/AddFileList'
import AddRelateList from '/src/szcomponent/QuickAdd/AddRelateList'
import CommonWords from '/src/szcomponent/CommonWords/index.vue'

import {fileSize, getFileTypeIcon, guid} from 'utils'
import {ElMessage, ElMessageBox} from "element-plus"


// 引入消息总线
const cxt = getCurrentInstance() //相当于Vue2中的this
const bus = cxt.appContext.config.globalProperties.$bus
const $wkUploadFile = cxt.appContext.config.globalProperties.$wkUploadFile

defineOptions({
  /** 跟进记录 下的 添加 有添加框的都需要*/
  name: 'LogAdd',
})

const properties = defineProps({
  // 展示相关商机关联
  showBusiness: {
    type: Boolean,
    default: false
  },
  // 展示相关商机关联
  showContacts: {
    type: Boolean,
    default: false
  },
  contacts: Array,
  // 首要联系人ID
  contactsId: [String, Number],
  // 跟进类型
  followTypes: Array,
  // 模块ID
  id: [String, Number],
  // 没有值就是全部类型 有值就是当个类型
  crmType: {
    type: String,
    default: ''
  },
})
const emits = defineEmits(['focus', 'send', 'close'])

// 默认闭合
const isUnfold = ref(false)
/** 输入法 */
const content = ref('')
/** 图片信息 */
const imgFiles = ref([])
// 关联商机注入的客户信息
const businessAction = ref({})
/** 图片信息 */
const files = ref([])
/** 关联商机信息 */
const showBusinessPopover = ref(false)
const business = ref([])
/** 关联联系人信息 */
const selectContactsId = ref('')
const followType = ref('')
// 下次联系时间
const nextTime = ref('')
/** 展示关联弹窗 */
const showRelativeType = ref('')
// 批次ID
const batchId = ref(guid())

const autosize = computed(() => {
  console.log("autsize", isUnfold.value)
  if (isUnfold.value) {
    return {minRows: 3, maxRows: 6}
  }
  // return {minRows: 3, maxRows: 6}
  return {minRows: 1, maxRows: 1}
})

function created() {
  selectContactsId.value = properties.contactsId || ''
  getDefaultFollowType()
}

created()


watch(() => properties.followTypes, () => {
  getDefaultFollowType()
})

watch(content, (val) => {
  const value = !!(val && val.length > 0)
  // todo 在源代码中也没有找到SlideView的实现
  // this.dispatch('SlideView', 'setEditClose', [value])
})

watch(() => properties.contactsId, () => {
  selectContactsId.value = properties.contactsId || ''
})

watch(() => properties.id, () => {
  businessAction.value = {type: 'condition', data: {moduleType: properties.crmType, customerId: properties.id}}
}, {
  immediate: true
})

/**
 * 跟进类型初始值
 */
function getDefaultFollowType() {
  if (properties.followTypes && properties.followTypes.length > 0) {
    followType.value = properties.followTypes[0].value
  } else {
    followType.value = ''
  }
}

/**
 * 重置数据
 */
// function resetInfo() {
const resetInfo = () => {
  console.log("initInfo 3")
  nextTime.value = ''
  isUnfold.value = false
  // 输入法
  content.value = ''
  // todo 在源代码中也没有找到SlideView的实现
  // this.dispatch('SlideView', 'setEditClose', [false])
  // 图片信息
  imgFiles.value = []
  // 图片信息
  files.value = []
  // 关联商机信息
  business.value = []
  // 关联联系人信息
  selectContactsId.value = properties.contactsId || ''
  // 展示关联弹窗
  showRelativeType.value = ''
  batchId.value = guid()
  getDefaultFollowType()
}

defineExpose({
  resetInfo
})


/**
 * 常用语选择
 */
function commonWordsSelect(data) {
  if (content.value) {
    // .$confirm('您选中的常用语将覆盖当前填写内容?', '提示', {
    //   confirmButtonText: '确定',
    //   cancelButtonText: '取消',
    //   type: 'warning',
    //   customClass: 'is-particulars'
    // })
    ElMessageBox.confirm('您选中的常用语将覆盖当前填写内容?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      customClass: 'is-particulars',
      type: 'warning'
    }).then(() => {
      content.value = data
    }).catch(() => {
    })
  } else {
    content.value = data
  }
}

/**
 * 快捷添加按钮
 */
function checkRelativeInfos(data) {
  if (showRelativeType.value == 'business') {
    business.value = data.data
  }
}

function barClick(type) {
  showRelativeType.value = type
  if (type == 'business') {
    showBusinessPopover.value = true
  } else if (type == 'file') {
    // .$refs.fileInput.click()
    cxt.refs.fileInput.click()
  } else if (type == 'img') {
    // .$refs.imgInput.click()
    cxt.refs.imgInput.click()
  }
}

/**
 * 图片选择出发
 */
function uploadFile(event) {
  let files = event.target.files
  if (files.length) {
    for (let index = 0; index < files.length; index++) {
      const file = files[index]
      if (file.type.indexOf('image') == -1 && showRelativeType.value == 'img') {
        // .$message.error('请上传正确的文件类型')
        ElMessage.error({message: '请上传正确的文件类型'})
        return
      }
    }

    let type = event.target.accept == 'image/*' ? 'img' : 'file'
    for (let index = 0; index < files.length; index++) {
      const file = files[index]
      uploadFileRequest(file, type)
    }
    event.target.value = ''
  }
}

/**
 * 文件上传
 */
function uploadFileRequest(file, type, result) {
  console.log("wkUploadFile",file)
  console.log("wkUploadFile",type)
  console.log("wkUploadFile",result)
  console.log("wkUploadFile",$wkUploadFile)
  $wkUploadFile.upload({
    file: file,
    params: {
      type: type,
      batchId: batchId.value
    }
  }).then(({res}) => {
    const data = res.data || {}
    data.size = fileSize(file.size)
    if (type == 'img') {
      imgFiles.value.push(data)
    } else {
      data['icon'] = getFileTypeIcon(file)
      files.value.push(data)
    }
    if (result) {
      result()
    }
  }).catch(() => {
  })
}

function focusStart() {
  cxt.refs.refNextTime.handleOpen() // 手动开启时间弹窗
}

/**
 * 图片附件删除
 */
function deleteImage(item, index) {
  deleteImgOrFile('image', item, index)
}

function deleteFile(item, index) {
  deleteImgOrFile('file', item, index)
}

function deleteImgOrFile(type, item, index) {
  // .$confirm('确定删除?', '提示', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'warning'
  // })
  ElMessageBox.confirm({
    message: '确定删除?',
    title: '提示',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    crmFileDeleteAPI({
      id: item.fileId
    })
        .then(res => {
          if (type == 'image') {
            imgFiles.value.splice(index, 1)
          } else {
            files.value.splice(index, 1)
          }
          // this.$message.success('操作成功')
          ElMessage.success({message: '操作成功'})
        })
        .catch(() => {
        })
  })
      .catch(() => {
      })
}

/**
 * 删除全部 type 1 是附件 2 是图片
 */
function deleteAllFile(type) {
  if (batchId.value) {
    // this.$confirm('确定删除?', '提示', {
    //   confirmButtonText: '确定',
    //   cancelButtonText: '取消',
    //   type: 'warning'
    // })
    ElMessageBox.confirm({
      message: '确定删除?',
      title: '提示',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      crmFileRemoveByBatchIdAPI({
        batchId: batchId.value,
        type
      }).then(res => {
        if (type == 2) {
          imgFiles.value = []
        } else {
          files.value = []
        }
        // $message.success('操作成功')
        ElMessage.success({message: '操作成功'})
      })
          .catch(() => {
          })
    })
        .catch(() => {
        })
  }
}

/**
 * 删除相关
 */
function deleteRelate(data, index) {
  business.value.splice(index, 1)
}

function inputFocus() {
  console.log("inputFocus")
  isUnfold.value = true
  nextTick(() => {
    //   // .$refs.textarea.focus()
    //   // cxt.refs.textarea.focus()
    //   改变 textarea 大小
    cxt.refs.textarea.resizeTextarea();
    emits('focus')
  })
}

/**
 * 发布
 */
function sendClick() {
  console.log("sendClick")
  emits('send', {
    id: properties.id,
    content: content.value,
    files: files.value,
    images: imgFiles.value,
    business: business.value,
    contactsId: selectContactsId.value,
    batchId: batchId.value,
    followType: followType.value,
    nextTime: nextTime.value
  })
}

/**
 * 关闭
 */
function close() {
  isUnfold.value = false
  emits('close')
}

</script>

<script>
// import {crmFileDeleteAPI, crmFileRemoveByBatchIdAPI} from '/src/api/common.js'

// import AddImageList from '/src/components/QuickAdd/AddImageList.vue'
// import AddFileList from '/src/components/QuickAdd/AddFileList.vue'
// import AddRelateList from '/src/components/QuickAdd/AddRelateList.vue'

// import {fileSize, getFileTypeIcon, guid} from '/src/utils/index.js'

import EmitterMixin from '/src/mixins/Emitter.js'
// import {defineAsyncComponent} from "vue";

export default {

  // components: {
  // CrmRelative: defineAsyncComponent(() => import('/src/components/CreateCom/CrmRelative.vue')),
  // AddImageList,
  // AddFileList,
  // AddRelateList,
  // CommonWords
  // },
  mixins: [EmitterMixin],
  // props: {},
  // data() {
  //   return {}
  // },
  // computed: {
  //
  // },
  // watch: {
  //
  // },


  // beforeDestroy() {
  // },
  // methods: {
  //
  // }
}
</script>

<style lang="scss" scoped>
.mix-content {
  position: relative;
  border: 1px solid #e6e6e6;
  border-radius: 3px;
  background-color: white;
  padding: 8px 8px 0;

  &-select {
    .el-select {
      width: 110px;
      margin-right: 8px;
    }

    .el-date-editor {
      width: 200px;
      margin-right: 8px;
    }
  }

  .i-cont {
    padding: 8px 0px;

    .wk-write {
      color: #e6e6e6;
      font-size: 15px;
    }
  }
}

.mix-content.unfold {
  padding: 0;

  .i-cont {
    padding: 8px 10px;
  }
}

.mix-content.unfold:hover {
  cursor: pointer;
  border-color: #c0c4cc;

  .i-cont {
    cursor: pointer;

    .wk-write {
      color: #2362FB;
    }

    :deep( .el-textarea__inner) {
      cursor: pointer;
    }
  }
}

.wk-close {
  border: 0;
  color: #d9d9d9;
  font-size: 22px;
  cursor: pointer;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 1;
  padding: 4px;
  transform: scale(0.8);
}

.wk-close:hover {
  color: #2362fb;
}

//.i-cont :deep(.el-textarea__inner) {
.i-cont :deep(.el-textarea__inner) {
  //影藏textarea的边框
  box-shadow: 0 0 0 0px;
  padding: 0;
}

.i-cont.unfold {
  :deep(.el-textarea) {
    width: calc(100% - 50px);
  }

  :deep(.el-textarea__inner) {
    overflow: hidden;
  }
}

/** 底部bar  */
.bar-cont {
  height: 30px;
  .handle-button {
    color: #666;
    font-size: 12px;

    :deep(i) {
      font-size: 12px;
      margin-right: 5px;
    }
  }

  .handle-button:hover {
    color: #2362FB;
  }
}

.file-input {
  display: none;
}

.send-btn {
  float: right;
  font-size: 12px;
  padding: 5px 9px;
  margin-top: -5px;
}
</style>
